package cn.edu.tju.wallet.service;

import cn.edu.tju.wallet.domain.WithdrawRule;
import cn.edu.tju.wallet.domain.WithdrawRule.RuleStatus;
import cn.edu.tju.wallet.dto.WithdrawRuleDTO;
import cn.edu.tju.wallet.repository.WithdrawRuleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class WithdrawRuleService {

    @Autowired
    private WithdrawRuleRepository withdrawRuleRepository;

    /**
     * 创建提现规则（参考充值规则示例）
     */
    @Transactional
    public WithdrawRule createWithdrawRule(WithdrawRuleDTO dto) {
        WithdrawRule rule = new WithdrawRule();
        rule.setName(dto.getName());
        rule.setFeeRate(dto.getFeeRate());
        rule.setMinFee(dto.getMinFee());
        rule.setMaxFee(dto.getMaxFee());
        rule.setStatus(RuleStatus.ACTIVE);
        return withdrawRuleRepository.save(rule);
    }

    /**
     * 更新提现规则（参考充值规则示例）
     */
    @Transactional
    public WithdrawRule updateWithdrawRule(Long id, WithdrawRuleDTO dto) {
        WithdrawRule rule = withdrawRuleRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("规则不存在"));
        // 更新字段
        rule.setName(dto.getName());
        rule.setFeeRate(dto.getFeeRate());
        rule.setMinFee(dto.getMinFee());
        rule.setMaxFee(dto.getMaxFee());
        return withdrawRuleRepository.save(rule);
    }

    /**
     * 删除提现规则（参考充值规则示例）
     */
    @Transactional
    public void deleteWithdrawRule(Long id) {
        withdrawRuleRepository.deleteById(id);
    }

    /**
     * 查询所有提现规则（参考充值规则示例）
     */
    public List<WithdrawRule> getAllRules() {
        return withdrawRuleRepository.findAll();
    }
}